﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;

namespace game
{
    public class FlyDownMovement
    {
        public float OldLayerHeight { get; private set; }
        public float NewLayerHeight { get; private set; }
        public float FlyDownAcc { get; set; }

        public bool Finished { get; private set; }

        private float balanceStartLayerOffset = 2500.0f;
        private float leanEndLayerOffset = 1000.0f;
        private float snapToLayerOffset = 20.0f;

        private bool leaning = false;
        private bool balancing = false;

        private RegularMovement regularMovement = null;

        public FlyDownMovement(RegularMovement regMove)
        {
            this.regularMovement = regMove;
        }

        public void Start(float oldLayerHeight, float newLayerHeight)
        {
            this.OldLayerHeight = oldLayerHeight;
            this.NewLayerHeight = newLayerHeight;
            leaning = true;
            Finished = false;
        }

        public float Lean(float curLean)
        {
            if (!balancing)
                return regularMovement.Lean(curLean, RegularMovement.LeanState.LEFT);
            else if (!leaning)
                return regularMovement.Lean(curLean, RegularMovement.LeanState.IDLE);
            else
                return curLean;
        }

        //public float Rotate(float curRot, float rotSpeed);

        public Vector3 Move(Vector3 curPos, Vector3 curRot)
        {
            if (balancing)
            {
                if (Math.Abs(curPos.Y - NewLayerHeight) < leanEndLayerOffset)
                {
                    curPos.Y += (NewLayerHeight - curPos.Y) * 0.5f;
                    leaning = false;
                    balancing = true;
                }

                if (Math.Abs(curPos.Y - NewLayerHeight) < snapToLayerOffset)
                {
                    curPos.Y = NewLayerHeight;
                    balancing = false;
                    Finished = true;
                }
            }

            if (leaning)
            {
                if (Math.Abs(curPos.Y - NewLayerHeight) < balanceStartLayerOffset)
                {
                    balancing = true;
                }

                if (curPos.Y != NewLayerHeight)
                {
                    float flyDownSpeed = curRot.Z * FlyDownAcc;
                    Vector3 wingMovement = Vector3.Transform(
                        Vector3.Left, Matrix.CreateRotationZ(curRot.Z) * Matrix.CreateRotationY(curRot.Y));
                    curPos += wingMovement * flyDownSpeed * MovementControl.DeltaTimeMs;
                }
            }

            return curPos;
        }
    }
}
